﻿using System;
using System.Reflection;
using System.Web;
using System.Web.Configuration;

namespace Nana.Web
{
  public static class FilterHelpers
  {
    /// <summary>
    /// System.Web
    /// </summary>
    private static readonly Assembly AssemblyWeb;

    /// <summary>
    /// System.Web.StaticFileHandler
    /// </summary>
    private static readonly Type TypeStaticFileHandler;

    /// <summary>
    /// Initlizate static members
    /// </summary>
    static FilterHelpers()
    {
      AssemblyWeb = typeof(IHttpHandler).Assembly;
      // get the Type object of System.Web.StaticFileHandler, use it later
      TypeStaticFileHandler = AssemblyWeb.GetType("System.Web.StaticFileHandler");
    }

    /// <summary>
    /// 推测指定的 handler 是否为静态文件服务 handler。
    /// </summary>
    /// <param name="handler"></param>
    /// <returns></returns>
    public static bool IsStaticHandler(this IHttpHandler handler)
    {
      // DefaultHttpHandler also count as static file handler, tho idk why
      return handler is DefaultHttpHandler || TypeStaticFileHandler.IsAssignableFrom(handler.GetType());
    }

    /// <summary>
    /// 推测指定的 HttpContext 是否持有静态文件的服务 handler。
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static bool IsStaticHandler(this HttpContext context)
    {
      return context.Handler.IsStaticHandler();
    }

    private const string emptyString = "";
    private const string preferredRenderingType = "preferredRenderingType";
    #region GetPreferredRenderingType

    public static string GetPreferredRenderingType(this HttpContext context)
    {
      return (null == context) ? emptyString
        : context.Request.GetPreferredRenderingType();
    }
    public static string GetPreferredRenderingType(this HttpRequest request)
    {
      return (null == request) ? emptyString
        : request.Browser.GetPreferredRenderingType();
    }
    public static string GetPreferredRenderingType(this HttpCapabilitiesBase capabilities)
    {
      return (null == capabilities) ? emptyString
        : capabilities[preferredRenderingType];
    }

    #endregion
    private const string preferredRenderingMime = "preferredRenderingMime";
    #region GetPreferredRenderingMime

    public static string GetPreferredRenderingMime(this HttpContext context)
    {
      return (null == context) ? emptyString
        : context.Request.GetPreferredRenderingMime();
    }
    public static string GetPreferredRenderingMime(this HttpRequest request)
    {
      return (null == request) ? emptyString
        : request.Browser.GetPreferredRenderingMime();
    }
    public static string GetPreferredRenderingMime(this HttpCapabilitiesBase capabilities)
    {
      return (null == capabilities) ? emptyString
        : capabilities[preferredRenderingMime];
    }

    #endregion
  }
}
